package com.ms.pda.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.Utils
import com.ms.architecture.base.BaseApplication
import com.ms.pda.messenger.AppMessenger
import com.ms.pda.model.KeyMap
import com.ms.pda.net.Request
import com.ms.pda.net.ResponseError
import com.ms.pda.repository.DB
import com.ms.pda.repository.DataSource
import com.ms.pda.utils.DialogUtil

/**
 * 在线离线校验模式
 */
inline fun handleCheckAction(
    actionMode: Boolean,
    onlineAction: () -> Int,
    offlineAction: () -> Int
): Int {
    return when (actionMode) {
        true -> {
            onlineAction()
        }
        else -> {
            offlineAction()
        }
    }
}

/**
 * 在线离线模式执行方法
 */
inline fun handleAction(
    actionMode: Boolean,
    onlineAction: () -> Unit,
    offlineAction: () -> Unit
) {
    when (actionMode) {
        true -> {
            onlineAction()
        }
        else -> {
            offlineAction()
        }
    }
}

abstract class BaseViewModel : ViewModel() {

    protected val dataSource: DataSource by lazy {
        val appMsg =
            ViewModelProvider((Utils.getApp() as BaseApplication))[AppMessenger::class.java]
        when (appMsg.networkMode.value) {
            KeyMap.ONLINE -> Request
            else -> DB
        }
    }

    protected val isOnLineCheck: Boolean by lazy {
        val appMsg =
            ViewModelProvider((Utils.getApp() as BaseApplication))[AppMessenger::class.java]
        when (appMsg.networkMode.value) {
            KeyMap.ONLINE -> true
            else -> false
        }
    }

    protected val appMsg: AppMessenger by lazy {
        ViewModelProvider((Utils.getApp() as BaseApplication))[AppMessenger::class.java]
    }

    protected fun handleResponseError(throwable: Throwable) {
        DialogUtil.getErrorDialog(ActivityUtils.getTopActivity(), ResponseError(throwable), null)
            .show()
    }

    protected fun handleResponseError(throwable: Throwable, from: Int) {
        DialogUtil.getErrorDialog(ActivityUtils.getTopActivity(), ResponseError(throwable), from)
            .show()
    }

}